package com.example.hanchen.yongkanggy.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.stream.Collectors;

public class ImageUploadTask implements Runnable {
    private String folderName;
    private String imagePath;
    private String uploadUrl;
    private UploadCallback callback;

    public ImageUploadTask(String folderName, String imagePath, String uploadUrl, UploadCallback callback) {
        this.folderName = folderName;
        this.imagePath = imagePath;
        this.uploadUrl = uploadUrl;
        this.callback = callback;
    }

    @Override
    public void run() {
        HttpURLConnection connection = null;
        DataOutputStream dos = null;
        FileInputStream fis = null;
        try {
            File file = new File(imagePath);
            URL url = new URL(uploadUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + "*****");
            connection.setRequestProperty("folder", folderName); // 设置文件夹名称
            connection.setRequestProperty("moduleName", "Question Feedback"); // 设置文件夹名称


            dos = new DataOutputStream(connection.getOutputStream());
            dos.writeBytes("--" + "*****" + "\r\n");
            dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + "\r\n");
            dos.writeBytes("Content-Type: image/jpeg" + "\r\n\r\n");

            fis = new FileInputStream(file);

            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, bytesRead);
            }

            dos.writeBytes("\r\n--" + "*****" + "--\r\n");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String serverResponse = new BufferedReader(new InputStreamReader(connection.getInputStream())).lines().collect(Collectors.joining("\n"));
                // 这里处理服务器返回的路径地址
                callback.onSuccess(serverResponse);
            } else {
                callback.onFailure("Server returned response code : " + responseCode);
            }

        } catch (Exception e) {
            callback.onFailure(e.getMessage());
        } finally {
            if (dos != null) {
                try {
                    dos.flush();
                    dos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public interface UploadCallback {
        void onSuccess(String response);
        void onFailure(String error);
    }
}

